let blockHost = [];

chrome.storage.local.get("blockHost", ({ blockHost }) => {
    blockHost = blockHost;
})

chrome.runtime.onMessage.addListener(async function (request, sender, sendResponse) {
    const host = request.host

    if (request.action === 'add') {
        if (!blockHost.includes(host)) {
            blockHost.push(host)
        }
    } else if (request.action === "remove") {
        let i = blockHost.indexOf(host);
        if (i > -1) {
            blockHost.splice(i, 1);
        }
    }
    await chrome.storage.local.set(
        {
            blockHost: blockHost
        })
    sendResponse({ action: request.action, stat: "success" })
});


chrome.webRequest.onBeforeRequest.addListener(

    function (details) {
        // debugger
        let url = new URL(details.initiator);
        let scriptUrl = new URL(details.url);
        let host = getTwoHost(url.host);
        if (!blockHost.includes(url.host)) {
            return { cancel: false }
        }
        if (host == getTwoHost(scriptUrl.host)) {
            return { cancel: false }
        }
        return { cancel: true }
        // return { redirectUrl: chrome.extension.getURL("returns.js") }; //returns.js是你要替换的js脚本
    },

    {

        urls: ["*://*/*"],  //你要拦截的url地址

        types: ["script"]       //拦截类型为script，
    },

    ["blocking"] //类型blocking为拦截,
);


function getTwoHost(host = "") {
    return host.split(".").slice(-2).join(".")
}